<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
        list-style: none;
    }

    .box {
        position: relative;
    }

    .box div {
        width: 100px;
        height: 100px;
        background-color: aquamarine;
        margin-top: 15px;
        position: absolute;
        left: 0;
    }
</style>

<body>
    <div class="box">
        <button>移动到400</button>
        <button>移动到800</button>
        <div></div>
    </div>
</body>
<script>
    var btn1 = document.getElementsByTagName('button')[0];
    // console.log(btn1);

    var btn2 = document.getElementsByTagName('button')[1];
    var div = document.getElementsByClassName('box')[0].getElementsByTagName('div')[0];
    // console.log(div);

    // var timer = null;
    // var current = 0;

    // btn1.onclick = function () {
    //   timer = setInterval(function () {
    //     var step = 9;
    //     current += step;
    //     if (current < 400) {
    //       div.style.left = current + 'px';
    //     } else {
    //       clearInterval(timer);
    //       div.style.left = '400px';

    //     }
    //   }, 20)
    // }
    // var current = div.offsetLeft;

    // console.log(current);

    function animate(ele, target) {
        clearInterval(ele.timer);

        // var timer = null;

        //这里一定要注意，不是style.left，那样是算不出来距离左边的距离的

        ele.timer = setInterval(function () {
            var current = div.offsetLeft;

            var step = (target - current) / 10;
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
            current += step;
            ele.style.left = current + 'px';
            if (current == target) {
                clearInterval(ele.timer);
            }
        }, 20)
    }
    btn1.onclick = function () {
        animate(div, 400);
    }
    btn2.onclick = function () {
        animate(div, 800);
    }

</script>

</html>